import MainLayout from '@/layout/MainLayout'
import { useEffect, useRef, useState } from 'react'
import { PianoRef } from '@/lib/music/AutoPlaySongController'
import { showToast } from '@/utils/toast'
import { dateFormat } from '@/utils/common'
import playSvg from '@/assets/svg/play.svg'
import pianoPlayerEvent from '@/event/pianoPlayerEvent'
import songListEvent from '@/event/songListEvent'
import { MusicPlayerSong } from '@/types/music'
import { musicInit } from '@/lib/music/data'
import styles from './music.module.scss'
import dynamic from 'next/dynamic'
const Piano = dynamic(() => import('@/views/music/Piano'), { ssr: false })
const MusicMenu = dynamic(() => import('@/views/music/MusicMenu'), {
  ssr: false,
})
const SongList = dynamic(() => import('@/views/music/SongList'), {
  ssr: false,
})
export default function MusicPage() {
  const pianoRef = useRef<PianoRef | null>(null)
  const [isRecordingState, setIsRecording] = useState(false)
  const isRecording = useRef(false)
  const [recordStartTime, setRecordStartTime] = useState(0)
  useEffect(() => {
    musicInit()
  }, [])
  useEffect(() => {
    isRecording.current = isRecordingState
  }, [isRecordingState])
  const startTime = useRef(0)
  const recordData = useRef<{ note: string; time: number }[]>([])
  useEffect(() => {
    startTime.current = recordStartTime || 0
  }, [recordStartTime])
  function stopRecordingHandle(): void {
    setIsRecording(false)
    const song: MusicPlayerSong = {
      name: '录制 ' + dateFormat(new Date(), 'MM-dd hh:mm:ss'),
      data: recordData.current,
      playerTime: Date.now() - startTime.current,
    }
    setRecordStartTime(0)
    if (song.playerTime < 5000) {
      showToast('录制时间太短,不能小于5秒,没有进行保存')
      return
    }
    if (recordData.current.length == 0) {
      showToast('没有录制到任何音符')
      return
    }
    songListEvent.emit('addSongList', song)
    // setSongList((prev) => [song, ...prev])
  }
  async function recordingHandle(): Promise<void> {
    recordData.current = []
    setRecordStartTime(Date.now())
    setIsRecording(true)
  }
  /**
   * 录制音符
   */
  useEffect(() => {
    if (isRecordingState) {
      const uninstall = pianoPlayerEvent.on('noteDown', (key) => {
        recordData.current.push({
          note: key.music,
          time: Date.now() - startTime.current,
        })
      })
      return () => {
        uninstall()
      }
    }
  }, [isRecordingState])

  return (
    <div className={styles['music-main']}>
      <div style={{ height: 50 }}></div>
      {/* {activeSong && <NoteVisualzation song={activeSong} />} */}
      {/* {!activeSong && <NoteVisualzation startTime={recordStartTime} />} */}
      <div
        style={{
          width: '100%',
          overflowX: 'auto',
        }}>
        <Piano ref={pianoRef} />
      </div>

      <MusicMenu />
      <div className={styles['buttons']}>
        {!isRecordingState && (
          <button
            className={styles['function-btn']}
            onClick={() => recordingHandle()}>
            录制
            <img className={styles['logo']} src={playSvg.src}></img>
          </button>
        )}
        {isRecordingState && (
          <button
            className={styles['function-btn']}
            onClick={() => stopRecordingHandle()}>
            结束录制
            <div className={styles['stop']}> </div>
          </button>
        )}
      </div>
      <SongList />
      {/* {activeSong && <MusicSpectrum />} */}
      {/* <div className={style['top-right']}></div>
        <div className={style['top-left']}>
          <MusicVisualization />
        </div> */}
    </div>
  )
}

MusicPage.getLayout = (page) => {
  return <MainLayout>{page}</MainLayout>
}
